package com.cuixichang.minimalism.core.security.design;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.cuixichang.minimalism.core.security.userdetails.CredentialDetail;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class DefaultJWTAnalysisDesign implements JWTAnalysisDesign{

    private static final List<String> filteredKeys = Arrays.asList("password");

    private static final byte[] jwtKeys = "token".getBytes(StandardCharsets.UTF_8);

    @Override
    public Authentication reverse(String token) {
        boolean verify = JWTUtil.verify(token, jwtKeys);
        Assert.isTrue(verify,"请求令牌校验未通过,请检查");
        JWT jwt = JWTUtil.parseToken(token);
        JSONObject payloads = jwt.getPayloads();
        CredentialDetail credentialDetail = BeanUtil.toBean(payloads, CredentialDetail.class);
        return new UsernamePasswordAuthenticationToken(credentialDetail, null,
                credentialDetail.getAuthorities());
    }

    @Override
    public String getToken(Authentication authenticate) {
        Assert.notNull(authenticate,"认证信息为空,请检查");
        CredentialDetail principal = (CredentialDetail) authenticate.getPrincipal();
        Map<String, Object> stringObjectMap = BeanUtil.beanToMap(principal);
        Collection<? extends GrantedAuthority> authorities = principal.getAuthorities();
        List<String> collect = authorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
        stringObjectMap.put("authorities", collect);
        filteredKeys.stream().forEach(key->stringObjectMap.remove(key));
        return JWTUtil.createToken(stringObjectMap, jwtKeys);
    }
}
